<template>
  <div class="user-manage">
    <div class="manage-content-header">
      <h1>用户管理</h1>
      <small class="">个人信息</small>
      <div>
        <ul class="content-header-nav">
          <li>
            后台管理
            <i class="el-icon-arrow-right"></i>
          </li>
          <li>
            用户管理
            <i class="el-icon-arrow-right"></i>
          </li>
          <li>个人中心</li>
        </ul>
      </div>
    </div>
    <div class="user-manage-container">
      <el-form
        :inline="true"
        :model="userMsgForm"
        label-width="100px"
        :rules="rules"
      >
        <!-- 用户名密码 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户名">
              <el-input
                v-model="userMsgForm.username"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="密码">
              <el-input
                type="password"
                show-password
                v-model.trim="userMsgForm.password"
                placeholder="不修改密码可以不填写~"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 昵称 邮箱 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="昵称" style="display: flex; width: 100%">
              <el-input
                v-model="userMsgForm.nickname"
                maxlength="10"
                show-word-limit
                placeholder="昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱">
              <el-input
                v-model="userMsgForm.email"
                placeholder="邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 头像地址 发送验证码 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="头像地址" style="display: flex; width: 100%">
              <el-input
                v-model="userMsgForm.avatarUrl"
                placeholder="头像地址"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="验证码" prop="emailCaptcha">
              <div style="display: flex">
                <el-input
                  v-model.trim="userMsgForm.emailCaptcha"
                  placeholder="请输入五位验证码"
                  maxlength="5"
                ></el-input>
                <el-button
                  :loading="sendEmailLoading"
                  :disabled="
                    userMsgForm.email.length === '' || sendCaptchaDisabled
                  "
                  @click="sendEmailCode"
                  >{{ btnText }}</el-button
                >
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 上传头像 -->
      <el-row>
        <el-col :span="23" :offset="1">
          <el-upload
            class="upload-demo"
            :http-request="uploadAvatar"
            action=""
            :limit="1"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              更改头像图片
              <span style="color: red"
                >TIPS:只能上传jpg/png/jpeg,不要太大哦!
                如果要重新添加请点击删除后再次添加</span
              >
            </div>
          </el-upload>
        </el-col>
      </el-row>

      <el-row style="margin-top: 10px">
        <el-col :span="16" :offset="8">
          <el-button
            type="primary"
            :disabled="uploadDisable"
            @click="uploadUserInfo"
            >修改信息</el-button
          >
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import getSession from "@/utils/getSession";
const sessionUtils = new getSession();
import myUtils from "@/utils/myUtils";
const utils = new myUtils();
import UserApiRequest from "@/api/UserApiRequest";
const userApiRequest = new UserApiRequest();
import BlogCommonApi from "@/api/BlogCommonApi";
const blogCommonApi = new BlogCommonApi();
import { uuid } from "vue-uuid";
export default {
  data() {
    var validateEmailCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱验证码"));
      }
      callback();
    };
    return {
      userMsgForm: {
        username: "",
        password: "",
        nickname: "",
        email: "",
        avatarUrl: "",
        emailCaptcha: "",
        emailKey: uuid.v1().slice(20),
      },
      fileList: [],
      sendCaptchaDisabled: false, // 发送验证码按钮判定
      sendEmailLoading: false, // 发送后加载图标判定
      uploadDisable: false, // 图片没上传完不准更新个人信息
      totalCount: 0,
      rules: {
        emailCaptcha: [{ validator: validateEmailCode, trigger: "blur" }],
      },
      // 已发送验证码的邮箱
      emailers: "",
    };
  },
  methods: {
    //点击修改信息后进行发送请求更新用户信息
    uploadUserInfo() {
      if (this.emailers !== this.userMsgForm.email) {
        this.$message({
          type: "error",
          message: "邮箱已修改请重新获取验证码",
        });
        return;
      }
      let data = {
        username: this.userMsgForm.username,
        nickname: this.userMsgForm.nickname,
        password: this.userMsgForm.password,
        email: this.userMsgForm.email,
        avatarUrl: this.userMsgForm.avatarUrl,
        emailCaptcha: this.userMsgForm.emailCaptcha,
        captchaKey: this.userMsgForm.emailKey,
        userId: this.$store.state.userInfo.uid,
      };

      if (!this.checkUpdateUserInfo(data)) {
        return;
      }
      userApiRequest.updateUserInfo(data).then((res) => {
        if (res.code === 206) {
          this.$message({
            type: "success",
            message: "更新个人信息成功",
          });
          // 更新用户数据后进行清空vuex 中的用户数据，以及退出登录
          sessionUtils.delStorage();
          this.$store.commit("logout");
          // 刷新本地缓存的数据
          localStorage.setItem("store", JSON.stringify(this.$store.state));
          // 退出登录请求
          userApiRequest.logOutUser().then((res) => {});
          // 回到首页
          this.$router.push({
            path: "/index",
          });
        }
        this.checkSendEmailMsg(res);
        if (res.code === -416) {
          this.$message({
            type: "warning",
            message: "更新个人信息失败",
          });
        }
        if (res.code === -411) {
          this.$message({
            type: "warning",
            message: "验证码输入错误",
          });
        }
        if (res.code === -412) {
          this.$message({
            type: "warning",
            message: "验证码已过期",
          });
        }
        if (res.code === -416) {
          this.$message({
            type: "error",
            message: "系统错误，更新失败",
          });
        }

        if (res.code === -418) {
          this.$message({
            type: "error",
            message: "不能重复提交数据哦！",
          });
        }
      });
    },

    // 发送验证码
    sendEmailCode() {
      let data = {
        email: this.userMsgForm.email,
        emailKey: this.userMsgForm.emailKey,
        isRegistry: false,
      };
      if (data.email.trim().length === 0) {
        this.$message({
          message: "邮箱不能为空哦!",
          type: "warning",
        });
        return;
      }
      // 请求发送验证码
      userApiRequest.getEmailCaptcha(data).then((res) => {
        // 检查邮箱状态
        this.checkSendEmailMsg(res);
        this.sendEmailLoading = true;
        if (res.code === 202) {
          this.$message({
            message: "邮箱发送成功,请登录您的邮箱进行查看",
            type: "success",
          });
          this.emailers = data.email;
          this.sendCaptchaDisabled = true;
          this.totalCount = 60;
          //this.getCode(); //60秒过倒计时过后才能调用的事件
          this.interval = setInterval(() => {
            this.totalCount--;
            if (this.totalCount === 0) {
              clearInterval(this.interval);
              this.totalCount = 0;
              this.sendCaptchaDisabled = false;
            }
          }, 1000);
        }
        if (res.code === -419) {
          this.$message.warning(res.msg);
        }
        this.sendEmailLoading = false;
      });
    },
    // 上传/更新用户头像
    uploadAvatar(param) {
      this.uploadDisable = true;
      const fileName = param.file.name;
      const fileSize = param.file.size;
      const file = param.file;
      // 检查类型 和 大小
      if (!utils.checkType(fileName)) {
        this.$message({
          message: "当前首页图片格式不正确,请检查一下你的图片",
          type: "warning",
        });
        this.uploadDisable = false;

        return;
      }
      if (!utils.checkSize(fileSize)) {
        this.$message({
          message: "上传的图片大小有点超出哦! 请重新选择一张",
          type: "warning",
        });
        this.uploadDisable = false;

        return;
      }
      const formData = new FormData();
      formData.append("avatarImage", file);
      blogCommonApi.uploadUserAvatar(formData).then((res) => {
        if (res.code === 0) {
          this.$message({
            message: "上传图片成功",
            type: "success",
          });
          this.userMsgForm.avatarUrl = res.data;
        }
        if (res.code === -1) {
          this.$message({
            message: "上传图片时发生未知错误!",
            type: "error",
          });
        }
        this.uploadDisable = false;
      });
    },
    // 检查发送邮箱的信息
    checkSendEmailMsg(res) {
      if (res.code === -414) {
        this.$message({
          message: "邮箱格式不正确,请重新输入!",
          type: "warning",
        });
      }
      if (res.code === -413) {
        this.$message({
          message: "当前邮箱已注册过!",
          type: "warning",
        });
      }
      if (res.code === -415) {
        this.$message({
          message: "邮箱发送失败,请检查您的网络问题",
          type: "warning",
        });
      }
    },
    // 检查更新的用户信息是否有异常 有异常则为false 不通过
    checkUpdateUserInfo(data) {
      if (data.emailCaptcha.split(" ").join("").length == 0) {
        this.$message({
          message: "验证码不能为空哦!",
          type: "warning",
        });
        return false;
      }
      if (data.nickname.split(" ").join("").length == 0) {
        this.$message({
          message: "昵称不能为空!",
          type: "warning",
        });
        return false;
      }

      if (data.username.split(" ").join("").length == 0) {
        this.$message({
          message: "用户名不能为空!",
          type: "warning",
        });
        return false;
      }
      if (data.email.split(" ").join("").length == 0) {
        this.$message({
          message: "邮箱不能为空!",
          type: "warning",
        });
        return false;
      }
      return true;
    },
  },
  mounted() {
    // 从vuex 中获取数据
    this.userMsgForm.avatarUrl = this.$store.state.userInfo.loginUrlAvatar;
    this.userMsgForm.username = this.$store.state.userInfo.username;
    this.userMsgForm.nickname = this.$store.state.userInfo.nickname;
    this.userMsgForm.email = this.$store.state.userInfo.email;
  },
  computed: {
    btnText() {
      return this.totalCount !== 0
        ? `${this.totalCount}秒再次获取`
        : "获取验证码";
    },
  },
};
</script>

<style scoped lang="scss">
.user-manage {
  .manage-content-header {
    position: relative;
    padding: 15px 15px 0 15px;
    h1 {
      font-size: 24px;
      font-weight: 400;
    }
    small {
      margin-left: 5px;
      font-size: 15px;
    }
    h1,
    small,
    ul {
      display: inline-block;
    }
    .content-header-nav {
      position: absolute;
      top: 30px;
      right: 15px;
      float: right;
      li:first-child {
        font-weight: 700;
        color: #303133;
      }
      li {
        color: #606266;
        float: left;
        font-size: 12px;
      }
    }
  }
}
.user-manage-container {
  position: relative;
  border-radius: 3px;
  background: #fff;
  border-top: 3px solid #3c8dbc;
  padding: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}
::v-deep .el-form-item__content {
  width: 100%;
}
.el-form-item {
  display: flex;
  width: 100%;
}
</style>
